package com.guass.nettyprotostuff.rpc.common;

import io.netty.channel.Channel;
import lombok.Data;

import java.net.SocketAddress;

@Data
public class Session {

    private String id;
    private String terminalMac;
    private Channel channel = null;
    private boolean isAuthenticated = false;
    private long currentFlowId = 0L;

    private long lastCommunicateTimeStamp = 0L;

    public Session() {
    }


    public static String buildId(Channel channel) {
        return channel.id().asLongText();
    }

    public static Session buildSession(Channel channel) {
        return buildSession(channel, null);
    }

    public static Session buildSession(Channel channel, String mac) {
        Session session = new Session();
        session.setChannel(channel);
        session.setId(buildId(channel));
        session.setTerminalMac(mac);
        session.setLastCommunicateTimeStamp(System.currentTimeMillis());
        return session;
    }

    public long getLastCommunicateTimeStamp() {
        return lastCommunicateTimeStamp;
    }

    public void setLastCommunicateTimeStamp(long lastCommunicateTimeStamp) {
        this.lastCommunicateTimeStamp = lastCommunicateTimeStamp;
    }

    public SocketAddress getRemoteAddr() {
        System.out.println(this.channel.remoteAddress().getClass());

        return this.channel.remoteAddress();
    }

    public boolean isAuthenticated() {
        return isAuthenticated;
    }

    public void setAuthenticated(boolean isAuthenticated) {
        this.isAuthenticated = isAuthenticated;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Session other = (Session) obj;
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Session [id=" + id + ", terminalMac=" + terminalMac + ", channel=" + channel + "]";
    }

    public synchronized long currentFlowId() {
        if (currentFlowId >= 0xffff) {
            currentFlowId = 0;
        }
        return currentFlowId++;
    }
}
